using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Web;
using System.Web.Mvc;
using EPiServer.Shell;
using EPiServer.Shell.Dashboard;
using EPiServer.Shell.Gadgets;
using EPiServer.Research.MobileCenter.Core;


namespace EPiServer.Research.MobileCenter
{
    /// <summary>
    /// This is a Controller for which we are able to get all the different gadgets and showing them
    /// </summary>
    public class MobileCenterDashboardController : Controller
    {

        /// <summary>
        /// Initializes a new instance of the <see cref="MobileCenterDashboardController"/> class.
        /// </summary>
        public MobileCenterDashboardController()
        {
            DashboardRepository = ShellContext.Instance.Container.GetExportedValue<IDashboardRepository>();
            GadgetFactory = ShellContext.Instance.Container.GetExportedValue<IGadgetFactory>();
          
        }

        public IGadgetFactory GadgetFactory { get; set; }

        public IDashboardRepository DashboardRepository { get; set; }

        /// <summary>
        /// When one single gadget is asked for this function gets the gadget information
        /// and returns the first view of the gadget
        /// </summary>
        /// <param name="gadgetId"></param>
        /// <returns></returns>
        public ActionResult GetGadget(Guid gadgetId)
        {
            Dashboard myDashboard = GetOrCreateDashboard();

            Gadget requestedGadget = null;
            if (!myDashboard.TryGetGadget(gadgetId, out requestedGadget))
            {
                throw new ArgumentException("The requested gadget does not exist");
            }
            
            return View(requestedGadget);
        }

        /// <summary>
        /// This function Gets the gadget based on name and returns a view of that gadget
        /// If you do not have access to edit mode you cannot see the gadget
        /// </summary>
        /// <param name="gadgetname"></param>
        /// <returns></returns>
        public ActionResult GetGadgetByName(string gadgetname)
        {

            if (!EPiServer.Security.PrincipalInfo.HasEditAccess)
            {
                throw new AccessViolationException("Access Denied, you do not have access to the edit mode");
            }
            
            Dashboard myDashboard = GetOrCreateDashboard();

            
            Tab t = null;
            foreach (Tab tab in myDashboard.Tabs)
            {
                if (tab.Name == GadgetUtil.MobileCenterTabName)
                {
                    t = tab;
                    break;
                }
            }

            if (t != null)
            {
                foreach (var item in t.Containers[0].Gadgets)
                {
                   
                    if (item.Title.Replace(" ", String.Empty) == gadgetname)
                    {
                        return View("GetGadget", item);
                    }
                }

                
            }

            throw new ArgumentException("The requested gadget does not exist");
        }

        /// <summary>
        /// Get or create the dashboard for the current user, and make sure it has a tab called MobileCenter
        /// </summary>
        protected Dashboard GetOrCreateDashboard()
        {
            Dashboard myDashboard;
            if (!DashboardRepository.TryGet(User.Identity.Name, out myDashboard))
            {
                // No dashboard exists, create a new one.
                myDashboard = new Dashboard { UserName = User.Identity.Name };
                AddMobileCenterTabAndGadgets(myDashboard);
                DashboardRepository.Create(myDashboard);
            }
            else
            {
                Tab t = null;
                bool hasMobileCenterTab = false;
                foreach (Tab tab in myDashboard.Tabs)
                {
                    if (tab.Name == GadgetUtil.MobileCenterTabName)
                    {
                        hasMobileCenterTab = true;
                        t = tab;
                        break;
                    }
                }

                if (!hasMobileCenterTab)
                {
                    // The dashboard exists, but lacks MobileCenter tab, so create it.
                    AddMobileCenterTabAndGadgets(myDashboard);
                    DashboardRepository.Save(myDashboard);
                }
                else
                {

                    foreach (Gadget gadgetTemplates in GadgetFactory.GetGadgetTemplates())
                    {
                        List<Gadget> list = new List<Gadget>();

                        if (!t.Containers[0].Gadgets.Contains(gadgetTemplates))
                        {
                            list.Add(gadgetTemplates);
                        }

                        foreach (Gadget item in list)
                        {
                            t.Containers[0].Gadgets.Add(item);
                        }
                       
                    }

                }
            }
            return myDashboard;
        }

        /// <summary>
        /// Adds the I phone tab and gadgets.
        /// </summary>
        /// <param name="dashboard">The dashboard.</param>
        private void AddMobileCenterTabAndGadgets(Dashboard dashboard)
        {
            TabLayout tabLayout = new TabLayout("1 Column",
                "1 Column",
                new Uri(Paths.ToShellResource("ClientResources/EPi/Views/Dashboard/LayoutDefinition-1Col.png"), UriKind.Relative),
                new List<LayoutPart>() { new LayoutPart("epi-grid-1", 1) });

            Tab MobileCenterTab = new Tab(GadgetUtil.MobileCenterTabName, tabLayout);

            // Add one gadget of each type to the tab
            foreach (Gadget gadgetTemplates in GadgetFactory.GetGadgetTemplates())
            {
                MobileCenterTab.Containers[0].Gadgets.Add(gadgetTemplates);
            }

            dashboard.Tabs.Add(MobileCenterTab);
        }
    }
}
